﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Happy.ExtentionMethods;
using Happy.PessimisticLock.Internal;

namespace Happy.PessimisticLock
{
    /// <summary>
    /// 基于内存的离线悲观锁管理器。
    /// </summary>
    public sealed class MemoryLockManager : ILockManager
    {
        private static readonly Dictionary<string, LockItem> _items = new Dictionary<string, LockItem>();

        /// <inheritdoc />
        public bool AcquireLock(string entity, string key, string owner, IExpirationPolicy expirationPolicy)
        {
            entity.MustNotNullAndNotWhiteSpace("entity");
            key.MustNotNullAndNotWhiteSpace("key");
            owner.MustNotNullAndNotWhiteSpace("owner");
            expirationPolicy.MustNotNull("expirationPolicy");

            var item = LockItem.Crete(entity, key, owner, expirationPolicy);

            lock (_items)
            {
                if (!IsLocked(item.Identifier))
                {
                    LockIt(item);

                    return true;
                }

                return IsLockedBy(item.Identifier, item.Owner);
            }
        }

        /// <inheritdoc />
        public void ReleaseLock(string entity, string key, string owner)
        {
            entity.MustNotNullAndNotWhiteSpace("entity");
            key.MustNotNullAndNotWhiteSpace("key");
            owner.MustNotNullAndNotWhiteSpace("owner");

            var identifier = LockItem.CreateIdentifier(entity, key);
            lock (_items)
            {
                if (!IsLockedBy(identifier, owner))
                {
                    throw new InvalidOperationException(string.Format(Resource.Messages.Error_CanNotReleaseLock, owner));
                }

                ReleaseLock(identifier);
            }
        }

        /// <inheritdoc />
        public void ReleaseLocks(string owner)
        {
            owner.MustNotNullAndNotWhiteSpace("owner");

            lock (_items)
            {
                foreach (var keypair in _items)
                {
                    if (keypair.Value.Owner == owner)
                    {
                        ReleaseLock(keypair.Value.Identifier);
                    }
                }
            }
        }

        /// <inheritdoc />
        public void ReleaseExpiredLocks()
        {
            lock (_items)
            {
                foreach (var keypair in _items)
                {
                    if (keypair.Value.ExpirationPolicy.IsExpired())
                    {
                        ReleaseLock(keypair.Value.Identifier);
                    }
                }
            }
        }

        private static bool IsLocked(string identifier)
        {
            return
                _items.ContainsKey(identifier)
                &&
                !_items[identifier].ExpirationPolicy.IsExpired();
        }

        private static bool IsLockedBy(string identifier, string owner)
        {
            if (!IsLocked(identifier))
            {
                return false;
            }

            return _items[identifier].Owner == owner;
        }

        private static void LockIt(LockItem item)
        {
            _items[item.Identifier] = item;
        }

        private static void ReleaseLock(string identifier)
        {
            _items.Remove(identifier);
        }
    }
}
